package com.uzykj.modules.front.web;

import com.uzykj.common.json.AjaxJson;
import com.uzykj.common.utils.CacheUtils;
import com.uzykj.common.utils.StringUtils;
import com.uzykj.core.persistence.Page;
import com.uzykj.core.web.BaseController;
import com.uzykj.modules.blog.entity.BlogCategory;
import com.uzykj.modules.blog.entity.BlogNote;
import com.uzykj.modules.blog.service.BlogCategoryService;
import com.uzykj.modules.blog.service.BlogNoteService;
import com.uzykj.modules.front.service.NoteService;
import com.uzykj.modules.sys.entity.User;
import com.uzykj.modules.sys.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author ghostxbh
 * @date 2020/7/24
 * @description 前台首页
 */
@Controller
@RequestMapping(value = "${frontPath}/")
public class HomeController extends BaseController {
    @Autowired
    private BlogCategoryService blogCategoryService;

    @Autowired
    private BlogNoteService blogNoteService;

    @Autowired
    private NoteService noteService;

    @ModelAttribute
    public void initCate() {
        // 初始化CategoryList cache
        List<BlogCategory> list = (List<BlogCategory>) CacheUtils.get(UserUtils.BLOG_CACHE, UserUtils.CACHE_BLOG_LIST);
        if (list == null || list.size() <= 0) {
            List<BlogCategory> allList = blogCategoryService.findAllList();
            CacheUtils.put(UserUtils.BLOG_CACHE, UserUtils.CACHE_BLOG_LIST, allList);
        }
    }

    /**
     * 首页
     *
     * @throws IOException
     */
    @RequestMapping(value = "home")
    public String home(HttpServletRequest request, HttpServletResponse response, Model model) throws IOException {
        List<BlogCategory> categoryList = (List<BlogCategory>) CacheUtils.get(UserUtils.BLOG_CACHE, UserUtils.CACHE_BLOG_LIST);

        Page<BlogNote> page = new Page<>();
        page.setPageSize(20);
        page.setOrderBy("like_count desc");
        Page<BlogNote> wellList = blogNoteService.findPage(page, new BlogNote());
        List<BlogNote> blogNoteList = Optional.ofNullable(wellList.getList())
                .orElse(new ArrayList<BlogNote>(0))
                .stream()
                .peek(blogNote ->
                        blogNote.setCreateBy(UserUtils.get(blogNote.getCreateBy().getId())))
                .collect(Collectors.toList());

        Page<BlogNote> jPage = new Page<>();
        jPage.setPageSize(1);
        jPage.setOrderBy("read_count desc");
        Page<BlogNote> selectedList = blogNoteService.findPage(jPage, new BlogNote());
        List<BlogNote> sList = Optional.ofNullable(selectedList.getList())
                .orElse(new ArrayList<BlogNote>(0))
                .stream()
                .peek(blogNote ->
                        blogNote.setCreateBy(UserUtils.get(blogNote.getCreateBy().getId())))
                .collect(Collectors.toList());

        List<User> userList = blogNoteService.topAuthor();

        model.addAttribute("categoryList", categoryList);
        model.addAttribute("wellList", blogNoteList);
        model.addAttribute("selectedList", sList);
        model.addAttribute("travelers", userList);
        return "modules/front/home";
    }

    @RequestMapping(value = "search", method = RequestMethod.GET)
    public String getNotes(@RequestParam(value = "search", required = false) String search,
                           @RequestParam(value = "city", required = false) String city,
                           @RequestParam(value = "label", required = false) String label,
                           @RequestParam(value = "category", required = false) String category,
                           @RequestParam(value = "creator", required = false) String creator,
                           HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<BlogNote> page = new Page<BlogNote>(request, response);
        page = noteService.search(page, city, search, label, category, creator);
        List<BlogNote> noteList = Optional.ofNullable(page.getList())
                .orElse(new ArrayList<BlogNote>())
                .stream()
                .peek(note -> note.setCreateBy(UserUtils.get(note.getCreateBy().getId())))
                .collect(Collectors.toList());

        String searchName = "";
        if (city != null) {
            searchName = city;
        } else if (label != null) {
            searchName = label;
        } else if (category != null) {
            searchName = category;
        } else if (creator != null) {
            User user = UserUtils.get(creator);
            if (user.getName() != null)
                searchName = user.getName();
            else
                searchName = "未搜索到用户";
        } else if (search != null) {
            searchName = search;
        }
        List<BlogCategory> categoryList = (List<BlogCategory>) CacheUtils.get(UserUtils.BLOG_CACHE, UserUtils.CACHE_BLOG_LIST);

        Page<BlogNote> jPage = new Page<>();
        jPage.setPageNo(1);
        jPage.setPageSize(1);
        jPage.setOrderBy("read_count desc");
        Page<BlogNote> selectedList = blogNoteService.findPage(jPage, new BlogNote());
        List<BlogNote> sList = Optional.ofNullable(selectedList.getList())
                .orElse(new ArrayList<BlogNote>(0))
                .stream()
                .peek(blogNote ->
                        blogNote.setCreateBy(UserUtils.get(blogNote.getCreateBy().getId())))
                .collect(Collectors.toList());

        List<User> userList = blogNoteService.topAuthor();

        model.addAttribute("searchName", searchName);
        model.addAttribute("noteList", noteList);
        model.addAttribute("categoryList", categoryList);
        model.addAttribute("selectedList", sList);
        model.addAttribute("travelers", userList);
        return "modules/front/search";
    }

    @RequestMapping(value = "search", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson getNoteList(@RequestParam(value = "search", required = false) String search,
                                @RequestParam(value = "city", required = false) String city,
                                @RequestParam(value = "label", required = false) String label,
                                @RequestParam(value = "category", required = false) String category,
                                @RequestParam(value = "creator", required = false) String creator,
                                HttpServletRequest request, HttpServletResponse response) {
        AjaxJson j = new AjaxJson();
        try {
            Page<BlogNote> page = new Page<BlogNote>(request, response);
            page = noteService.search(page, city, search, label, category, creator);
            j.setSuccess(true);
            j.setMsg("ok");
            j.put("pageList", page);
        } catch (Exception e) {
            logger.error("page note error", e);
            j.setSuccess(false);
            j.setMsg("获取文章分页失败");
        }
        return j;
    }
}
